<template>
  <view class="property-page">
    <!-- 服务卡片网格 -->
    <view class="service-grid">
      <!-- 物业费查询卡片 -->
      <service-card
        title="我的物业费"
        description="查询物业费、水电费等费用"
        icon-name="search"
        theme-color="#3498db"
        @click="goToMyFees"
      />
      
      <!-- 我的卫生费卡片 -->
      <service-card
        title="我的卫生费"
        description="查询卫生费缴费情况"
        icon-name="recycle"
        theme-color="#16a085"
        @click="goToSanitationFees"
      />
      
      <!-- 我的燃气费卡片 -->
      <service-card
        title="我的燃气费"
        description="查询燃气费缴费情况"
        icon-name="fire"
        theme-color="#e67e22"
        @click="goToGasFees"
      />
      
      <!-- 我的电费卡片 -->
      <service-card
        title="我的电费"
        description="查询电费缴费情况"
        icon-name="flash"
        theme-color="#f39c12"
        @click="goToElectricityFees"
      />
      
      <!-- 我的水费卡片 -->
      <service-card
        title="我的水费"
        description="查询水费缴费情况"
        icon-name="water"
        theme-color="#3498db"
        @click="goToWaterFees"
      />
      
      <service-card
        v-for="service in serviceList" 
        :key="service.id"
        :title="service.title"
        :description="service.description"
        :icon-name="service.icon"
        :theme-color="service.color"
        @click="handleService(service)"
      />
      
      <!-- 物业公告 -->
      <service-card
        title="物业公告"
        description="查看最新物业通知公告"
        icon-name="file-text"
        theme-color="#e74c3c"
        @click="showNotices"
      />
      
      <!-- 联系我们 -->
      <service-card
        title="联系我们"
        description="物业电话、微信客服等联系方式"
        icon-name="phone"
        theme-color="#27ae60"
        @click="showContact"
      />
    </view>

    <!-- 物业费查询弹窗 -->
    <u-popup v-model="showFeeQueryPopup" mode="center" :round="10" width="90%">
      <view class="fee-query-popup">
        <view class="popup-header">
          <text class="popup-title">物业费查询</text>
          <u-icon name="close" @click="showFeeQueryPopup = false" size="20"></u-icon>
        </view>
        <view class="fee-query-form">
          <u-form-item label="房号">
            <u-input 
              v-model="feeQuery.roomNumber"
              placeholder="请输入房号"
              clearable
            ></u-input>
          </u-form-item>
          <u-form-item label="费用类型">
            <u-radio-group v-model="feeQuery.feeType" placement="row">
              <u-radio name="property" label="物业费"></u-radio>
              <u-radio name="utility" label="水电费"></u-radio>
              <u-radio name="gas" label="燃气费"></u-radio>
              <u-radio name="sanitation" label="卫生费"></u-radio>
            </u-radio-group>
          </u-form-item>
          <u-button 
            type="primary" 
            text="查询费用"
            :loading="querying"
            @click="queryFee"
            size="medium"
          ></u-button>
        </view>
        
        <!-- 费用查询结果 -->
        <view v-if="feeResult" class="fee-result">
          <view class="fee-item">
            <text class="fee-label">账单金额：</text>
            <text class="fee-amount">¥{{ feeResult.amount }}</text>
          </view>
          <view class="fee-item">
            <text class="fee-label">缴费状态：</text>
            <u-tag :text="feeResult.statusText" :type="feeResult.statusType" size="mini"></u-tag>
          </view>
          <view class="fee-item">
            <text class="fee-label">截止日期：</text>
            <text class="fee-date">{{ feeResult.dueDate }}</text>
          </view>
          <u-button 
            v-if="feeResult.status === 1"
            type="success" 
            text="立即缴费"
            @click="handlePayment"
            size="small"
          ></u-button>
        </view>
      </view>
    </u-popup>

    <!-- 物业公告弹窗 -->
    <u-popup v-model="showNoticesPopup" mode="center" :round="10" width="90%">
      <view class="notices-popup">
        <view class="popup-header">
          <text class="popup-title">物业公告</text>
          <u-icon name="close" @click="showNoticesPopup = false" size="20"></u-icon>
        </view>
        <view class="notice-list">
          <view 
            v-for="notice in notices" 
            :key="notice.id"
            class="notice-item"
            @click="viewNotice(notice)"
          >
            <view class="notice-content">
              <text class="notice-title">{{ notice.title }}</text>
              <text class="notice-time">{{ notice.time }}</text>
            </view>
            <view class="notice-badge" v-if="notice.isImportant">
              <u-tag text="重要" type="error" size="mini"></u-tag>
            </view>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 联系我们弹窗 -->
    <u-popup v-model="showContactPopup" mode="center" :round="10" width="90%">
      <view class="contact-popup">
        <view class="popup-header">
          <text class="popup-title">联系我们</text>
          <u-icon name="close" @click="showContactPopup = false" size="20"></u-icon>
        </view>
        <view class="contact-list">
          <view class="contact-item" @click="callPhone('400-123-4567')">
            <u-icon name="phone" color="#2d8cf0" size="20"></u-icon>
            <text class="contact-text">物业电话：400-123-4567</text>
            <u-icon name="arrow-right" color="#999" size="16"></u-icon>
          </view>
          <view class="contact-item" @click="copyWechat">
            <u-icon name="weixin" color="#07c160" size="20"></u-icon>
            <text class="contact-text">微信客服：smart_property</text>
            <u-icon name="arrow-right" color="#999" size="16"></u-icon>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
/**
 * 物业管理页面 - 重构版本
 * @author Wu.Liang
 * @date 2025-06-26
 * @version 3.0 - 根据系统设计调整方案重构，统一物业接口
 */

import { ref, reactive, onMounted } from 'vue'
import { propertyFeeApi, utilityFeeApi, gasFeeApi, sanitationFeeApi } from '@/api/property'
import { hasMenuPermission } from '@/utils/permission'
import { useAuthStore } from '@/store'
import ServiceCard from '@/components/ServiceCard.vue'

// 物业费查询数据
const feeQuery = reactive({
  roomNumber: '',
  feeType: 'property'
})

// 查询状态
const querying = ref(false)

// 费用查询结果
const feeResult = ref(null)

// 弹窗显示状态
const showFeeQueryPopup = ref(false)
const showNoticesPopup = ref(false)
const showContactPopup = ref(false)

// 服务列表 - 改为子菜单结构
const serviceList = reactive([
  {
    id: 'owner-info',
    title: '业主信息完善',
    description: '完善个人业主信息',
    icon: 'user',
    color: '#9b59b6',
    url: '/pages/property/owner-info'
  },
  {
    id: 'repair',
    title: '我要报修',
    description: '在线报修申请',
    icon: 'tools',
    color: '#ff9500',
    url: '/pages/property/repair'
  },
  {
    id: 'my-repair',
    title: '我的报修',
    description: '查看报修记录',
    icon: 'list',
    color: '#2ed573',
    url: '/pages/property/my-repair'
  }
])

// 公告数据
const notices = ref([])

// 跳转到我的物业费页面
const goToMyFees = () => {
  uni.navigateTo({
    url: '/pages/property/my-fees'
  })
}

// 跳转到我的卫生费页面
const goToSanitationFees = () => {
  uni.navigateTo({
    url: '/pages/property/sanitation-fees'
  })
}

// 跳转到我的燃气费页面
const goToGasFees = () => {
  uni.navigateTo({
    url: '/pages/property/gas-fees'
  })
}

// 跳转到我的电费页面
const goToElectricityFees = () => {
  uni.navigateTo({
    url: '/pages/property/electricity-fees'
  })
}

// 跳转到我的水费页面
const goToWaterFees = () => {
  uni.navigateTo({
    url: '/pages/property/water-fees'
  })
}

// 显示物业费查询弹窗
const showFeeQuery = () => {
  showFeeQueryPopup.value = true
}

// 显示物业公告弹窗
const showNotices = () => {
  showNoticesPopup.value = true
}

// 显示联系我们弹窗
const showContact = () => {
  showContactPopup.value = true
}

// 查询物业费
const queryFee = async () => {
  if (!feeQuery.roomNumber) {
    uni.showToast({
      title: '请输入房号',
      icon: 'none'
    })
    return
  }
  
  querying.value = true
  try {
    // 根据费用类型调用对应的API
    let response
    if (feeQuery.feeType === 'property') {
      response = await propertyFeeApi.getPropertyFeeList({
        roomNumber: feeQuery.roomNumber
      })
    } else if (feeQuery.feeType === 'utility') {
      response = await utilityFeeApi.getUtilityFeeList({
        roomNumber: feeQuery.roomNumber
      })
    } else if (feeQuery.feeType === 'gas') {
      response = await gasFeeApi.getGasFeeList({
        roomNumber: feeQuery.roomNumber
      })
    } else if (feeQuery.feeType === 'sanitation') {
      response = await sanitationFeeApi.getSanitationFeeList({
        roomNumber: feeQuery.roomNumber
      })
    }
    
    if (response && response.data && response.data.length > 0) {
      const latestFee = response.data[0]
      feeResult.value = {
        amount: latestFee.amount,
        status: latestFee.paymentStatus,
        statusText: getStatusText(latestFee.paymentStatus),
        statusType: getStatusType(latestFee.paymentStatus),
        dueDate: latestFee.dueDate
      }
    } else {
      feeResult.value = {
        amount: '0.00',
        status: 2,
        statusText: '暂无费用',
        statusType: 'info',
        dueDate: '-'
      }
    }
  } catch (error) {
    console.error('查询费用失败:', error)
    uni.showToast({
      title: '查询失败，请重试',
      icon: 'none'
    })
  } finally {
    querying.value = false
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未支付',
    1: '已支付',
    2: '逾期',
    3: '部分支付'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',  // 未支付 - 警告
    1: 'success',  // 已支付 - 成功
    2: 'error',    // 逾期 - 错误
    3: 'info'      // 部分支付 - 信息
  }
  return typeMap[status] || 'info'
}

// 处理缴费
const handlePayment = () => {
  uni.navigateTo({
    url: `/pages/property/payment?roomNumber=${feeQuery.roomNumber}&feeType=${feeQuery.feeType}`
  })
}

// 处理服务点击
const handleService = (service) => {
  if (service.url) {
    uni.navigateTo({
      url: service.url
    })
  }
}

// 查看公告详情
const viewNotice = (notice) => {
  uni.navigateTo({
    url: `/pages/property/notice-detail?id=${notice.id}`
  })
}

// 拨打电话
const callPhone = (phone) => {
  uni.makePhoneCall({
    phoneNumber: phone,
    success: () => {
      console.log('拨打电话成功')
    },
    fail: (err) => {
      console.error('拨打电话失败', err)
    }
  })
}

// 复制微信号
const copyWechat = () => {
  uni.setClipboardData({
    data: 'smart_property',
    success: () => {
      uni.showToast({
        title: '微信号已复制',
        icon: 'success'
      })
    }
  })
}

// 加载公告列表
const loadNotices = async () => {
  try {
    // 模拟数据，实际应该调用API
    notices.value = [
      {
        id: 1,
        title: '关于小区电梯维修的通知',
        time: '2025-01-21 10:30',
        isImportant: true
      },
      {
        id: 2,
        title: '春节期间物业服务安排',
        time: '2025-01-20 15:20',
        isImportant: false
      },
      {
        id: 3,
        title: '小区环境整治活动通知',
        time: '2025-01-19 09:15',
        isImportant: false
      }
    ]
  } catch (error) {
    console.error('加载公告失败:', error)
  }
}

onMounted(() => {
  loadNotices()
})
</script>

<style lang="scss" scoped>
.property-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 16px;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  
  // 小屏幕适配
  @media screen and (max-width: 375px) {
    padding: 12px;
  }
  
  // 中等屏幕适配
  @media screen and (min-width: 376px) and (max-width: 768px) {
    padding: 16px;
  }
  
  // 大屏幕适配
  @media screen and (min-width: 769px) {
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
  }
}

// ServiceCard组件样式已移至组件内部，此处不再重复定义

.service-grid {
  margin-bottom: 16px;
  width: 100%;
  
  // 确保网格内的卡片能够正确自适应
  .service-card {
    width: 100%;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

// 弹窗样式
.fee-query-popup,
.notices-popup,
.contact-popup {
  background: white;
  border-radius: 12px;
  padding: 20px;
  max-height: 80vh;
  overflow-y: auto;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;
    
    .popup-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

.fee-query-form {
  .u-form-item {
    margin-bottom: 16px;
  }
}

.fee-result {
  margin-top: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  
  .fee-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .fee-label {
      color: #666;
      font-size: 28rpx;
    }
    
    .fee-amount {
      color: #ff4757;
      font-size: 32rpx;
      font-weight: bold;
    }
    
    .fee-date {
      color: #333;
      font-size: 28rpx;
    }
  }
}

.notice-list {
  .notice-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .notice-content {
      flex: 1;
      
      .notice-title {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 4px;
        word-break: break-all;
      }
      
      .notice-time {
        display: block;
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .notice-badge {
      margin-left: 12px;
      flex-shrink: 0;
    }
  }
}

.contact-list {
  .contact-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .contact-text {
      flex: 1;
      margin-left: 12px;
      font-size: 28rpx;
      color: #333;
      word-break: break-all;
    }
  }
}

/* 横屏适配 */
@media screen and (orientation: landscape) {
  .property-page {
    min-height: 100vh;
    padding: 20px;
  }
  
  .service-grid {
    padding-bottom: 20px;
  }
}
</style> 